import React, {memo, useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";

import "./realtimeCurve.css";
import Title from "../../../../../components/Title/Title";
import {deepClone, getAnalysisInfo} from "../../../../../common/utils";
import PlateTable from "../../../../../components/plateTable/PlateTable";
import {FluorescenceCanvas, FluorescenceEntity, TemperatureCanvas} from "../../../../../common/canvas";
import {WELLS_COLUMN, WELLS_ROW} from "../../../plate/config";
import {AMPLIFICATION, MELT} from "../../../protocol/config";
import {saveExportObj, saveExportObjCn} from "../../../export/store/actionCreators";
import {saveRunTargetSelectedArr} from "./store/actionCreators";
import {saveAnalysisShowLineArr} from "../../../plate/store/actionCreators";

export default memo(function RealtimeCurve(props) {
    const dispatch = useDispatch();
    const {data, runTargetSelectedArr, pcrAllCycle, meltGrad, currentTempData, analysisShowLineArr, pcrData, meltData, exportObj, exportObjCn, isCN} = useSelector(state => ({
        data: state.dataReducer.data,
        currentTempData: state.runReducer.currentTempData,
        pcrData: state.runReducer.pcrData,
        meltData: state.runReducer.meltData,
        exportObj: state.exportReducer.exportObj,
        exportObjCn: state.exportReducer.exportObjCn,
        analysisShowLineArr: state.plateReducer.analysisShowLineArr,//  包含可以画线的well(同时有target和sampleName)
        pcrAllCycle: state.protocolReducer.pcrAllCycle,
        meltGrad: state.protocolReducer.meltGrad,
        runTargetSelectedArr: state.realtimeCurveReducer.runTargetSelectedArr, //  保存Target Setting中Opt被选中的target
        isCN: state.languageReducer.isCN
    }));
    const [plateView, setPlateView] = useState(false);
    const [target, setTarget] = useState(() => {
        let targetMap = new Map(),
            result = [];
        data.wells.forEach(item => item.targets.forEach(item_ => targetMap.set(item_.name, {...item_, opt: true})));
        targetMap.forEach(value => result.push(value));
        return result;
    });  //  target条目
    const [pcrAllCycle_, setPcrAllCycle] = useState(() => {
        let pcrArr = data.protocol.stages.filter(item => item.state === AMPLIFICATION);
        return pcrArr.reduce((preValue, currentValue) => {
            return preValue + currentValue.cycle;
        }, 0);
    })
    const curveStyle = {
        paddingLeft: 100,
        paddingTop: 30,
        paddingBottom: 20,
        paddingRight: 10,
        dataPaddingLeft: 40,
        dataPaddingBottom: 40,
        dataPaddingTop: 40,
        dataPaddingRight: 40,
        axisTitleTop: "Amplification",
        axisTitleLeft: "RFU(10^3)",
        axisTitleLeftPadding: 50,
        maxX: pcrAllCycle_,
        axisTitleTopColor: "#fff",
        axisTitleLeftColor: "#fff",
        axisColor: "#fff",
        axisNumberColor: "#fff",
        xDataStart: 1
        // xBase1: true
    };
    const tempStyle = {
        paddingLeft: 60,
        paddingTop: 30,
        paddingBottom: 50,
        paddingRight: 30,
        dataPaddingLeft: 0,
        dataPaddingBottom: 0,
        dataPaddingTop: 40,
        dataPaddingRight: 60,
        axisTitleTop: "Temperature Curve",
        axisTitleTopColor: "#000",
        maxY: 110,
        initMaxX: 1000
    };
    const pcrControl = data.protocol.stages.some(item => item.state === AMPLIFICATION); //  protocol界面是否由AMPLIFICATION
    const meltControl = data.protocol.stages.some(item => item.state === MELT); //  protocol界面是否由MELT
    let realtimeTemp;
    let realtimeMelt;
    let cloneRunTargetSelectedArr = [];
    let cloneTarget = [];

    //  先运行实验后进行设置导致 lineData 没有更新,在这里重新计算一下
    useEffect(() => {
        let lineData = getAnalysisInfo(data);
       /* console.log(lineData);
        console.log(lineData.analysisShowLineArr);*/
        dispatch(saveAnalysisShowLineArr(lineData.analysisShowLineArr)); //  保存可以画线的数据(只有target和sample同时选择后才能画线)
        dispatch(saveRunTargetSelectedArr([...new Set(lineData.targetSelectedArr)]));
    }, []);

    useEffect(() => {
        let meltDom = document.getElementById("realtimeMelt");
        let tempDom = document.getElementById("realtimeTemp");
        let realtimeCurve = FluorescenceCanvas.init("realtimeCurve", curveStyle);
        // debugger
        realtimeCurve.setMaxX(pcrAllCycle_);
        // 画quantification
        pcrControl && analysisShowLineArr.forEach(item => {
            if (!data.wells[item.id].show || !runTargetSelectedArr.includes(item.target.value)) {
                return;
            }
            const azdIndex = item.col * 8 + item.row; //  AZD中的数据是竖着算的,D3对应19,cqa中D3对应38
            realtimeCurve.addEntity(FluorescenceEntity.getInstance({
                id: item.id,
                dataList: pcrData[`channel${item.channelIndex + 1}`]?.[azdIndex] || [],
                color: item.color,
                text: WELLS_ROW[item.row] + WELLS_COLUMN[item.col],
                textColor: "#fff"
            }));
        });
        if (meltDom && meltControl) {
            let meltStep = data.protocol.stages.filter(item => item.state === MELT)[0];
            realtimeMelt = FluorescenceCanvas.init("realtimeMelt", {
                paddingLeft: 50,
                paddingTop: 30,
                paddingBottom: 20,
                paddingRight: 10,
                dataPaddingLeft: 40,
                dataPaddingBottom: 40,
                dataPaddingTop: 40,
                dataPaddingRight: 40,
                axisTitleTop: "Melt Curve",
                minX: meltGrad.minX,
                maxX: meltGrad.maxX,
                xDataStart: meltStep.steps[0].temperature,
                xDataGradient: meltStep.steps[0].gradient
            });
            // 画melt
            analysisShowLineArr.forEach(item => {
                if (!data.wells[item.id].show || !runTargetSelectedArr.includes(item.target.value)) {
                    return;
                }
                const azdIndex = item.col * 8 + item.row; //  AZD中的数据是竖着算的,D3对应19,cqa中D3对应38
                realtimeMelt.addEntity(FluorescenceEntity.getInstance({
                    id: item.id,
                    dataList: meltData[azdIndex] || [],
                    color: item.color,
                    text: WELLS_ROW[item.row] + WELLS_COLUMN[item.col]
                }));
            });
        }
        if (tempDom) {
            realtimeTemp = TemperatureCanvas.init("realtimeTemp", tempStyle);
            //  画温度线
            realtimeTemp.drawLidAndSampleTemperature(currentTempData);
        }
        // 设置Export对象
        tempDom && setTimeout(() => {
            let cloneExportObj = {};
            cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
            if (document.getElementById("realtimeTempImgUrl")) {
                cloneExportObj.run.imgTemperatureCurve = document.getElementById("realtimeTempImgUrl").toDataURL().split(",")[1];
            }
            isCN ? dispatch(saveExportObjCn(cloneExportObj))
                : dispatch(saveExportObj(cloneExportObj));
        });
        return () => {
            realtimeCurve.destroyCanvas();
            tempDom && realtimeTemp.destroyCanvas();
            meltDom && meltControl && realtimeMelt.destroyCanvas();
        };
    }, [data, currentTempData, runTargetSelectedArr, plateView, pcrData, meltData, pcrAllCycle, data.protocol.stages, meltGrad]);

    //  Target Setting点击Opt操作
    function targetSettingSelect(indey) {
        cloneTarget = deepClone(target, cloneTarget);
        cloneRunTargetSelectedArr = deepClone(runTargetSelectedArr, cloneRunTargetSelectedArr);
        cloneTarget[indey].opt = !cloneTarget[indey].opt;
        cloneRunTargetSelectedArr = cloneTarget.filter(item => item.opt).map(item => item.name);
        setTarget(cloneTarget);
        dispatch(saveRunTargetSelectedArr(cloneRunTargetSelectedArr));
    }

    function chooseWell(position) {
        //  TODO: 选择well后画对应的线
    }

    return (
        <div className="runPageRealtimeCurve">
            <section className="scrollBarStyle">
                <div id="realtimeCurve"/>
            </section>
            {
                plateView
                    ? <section className="runPagePlateView">
                        <PlateTable wellsClickAction={chooseWell}/>
                        <div>
                            <Title name={isCN ? "目标基因设置" : "Target Setting"}/>
                            <ul>
                                <li>{isCN ? "选择" : "Opt"}</li>
                                <li>{isCN ? "基因" : "Target"}</li>
                                <li>{isCN ? "颜色" : "Color"}</li>
                                <li>{isCN ? "通道" : "Channel"}</li>
                            </ul>
                            <section className="scrollBarStyle">
                                {
                                    target.map((item, index) => (
                                        <ul key={item.name}>
                                            <li className={item.opt ? "selectedStyle" : ""}
                                                onClick={() => targetSettingSelect(index)}/>
                                            <li>{item.name}</li>
                                            <li>
                                                <div style={{backgroundColor: `${item.color}`}}/>
                                            </li>
                                            <li>{item.channel}</li>
                                        </ul>
                                    ))
                                }
                            </section>
                        </div>
                    </section>
                    : <section>
                        <div className="scrollBarStyle">
                            <div id="realtimeTemp"/>
                        </div>
                        <div className="scrollBarStyle">
                            <div id="realtimeMelt"/>
                        </div>
                    </section>
            }
            <div onClick={() => setPlateView(!plateView)}>
                {plateView
                    ?
                    isCN ? "返回上一页" : "Previous"
                    :
                    isCN ? "孔板视图" : "Plate View"
                }</div>
        </div>
    );
});